package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.CoefficentVO;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.insurance.mapper.CoefficentMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.Coefficent;
import com.itheima.sfbx.insurance.pojo.InsuranceCoefficent;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICoefficentService;
import com.itheima.sfbx.insurance.service.IInsuranceCoefficentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description：系数项服务实现类
 */
@Slf4j
@Service
public class CoefficentServiceImpl extends ServiceImpl<CoefficentMapper, Coefficent> implements ICoefficentService {

    @Autowired
    private ICategoryCoefficentService categoryCoefficentService;

    @Autowired
    private IInsuranceCoefficentService insuranceCoefficentService;

    @Override
    public Page<CoefficentVO> findPage(CoefficentVO coefficentVO, int pageNum, int pageSize) {

        Page<Coefficent> page = this.page(new Page<>(pageNum, pageSize), queryWrapper(coefficentVO));

        return BeanConv.toPage(page, CoefficentVO.class);
    }

    @Override
    public CoefficentVO findById(String coefficentId) {
        //TODO
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CoefficentVO save(CoefficentVO coefficentVO) {

        Integer count = lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .eq(Coefficent::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        if(count>0){
            log.error("新增失败，该key已存在");
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }

        Coefficent coefficent = BeanConv.toBean(coefficentVO, Coefficent.class);

        save(coefficent);

        return BeanConv.toBean(coefficent, CoefficentVO.class);
    }

    @Override
    @Transactional
    public Boolean update(CoefficentVO coefficentVO) {

        // 判断是否存在该数据
        Coefficent bean = getById(coefficentVO.getId());
        if(bean==null){
            log.error("该系数项不存在");
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }

        // 查询除自己以外的key是否重复
        Integer count = lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .ne(Coefficent::getId, coefficentVO.getId())
                .count();

        if(count > 0){
            log.error("该系数key已存在");
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }

        int num = judgeMiddleTableDataExist(coefficentVO.getCoefficentKey());
        if(num > 0){
            log.error("该系数key存在关联关系");
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }

        return updateById(BeanConv.toBean(coefficentVO, Coefficent.class));
    }



    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {

        Coefficent bean = getById(checkedIds[0]);
        if(bean==null){
            log.error("删除失败，该数据不存在");
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }

        int count1 = judgeMiddleTableDataExist(bean.getCoefficentKey());

        if(count1 > 0){
            log.error("该系数项已被关联，无法删除");
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }

        int result = baseMapper.deleteById(checkedIds[0]);

        return result > 0;
    }

    @Override
    public List<CoefficentVO> findList(CoefficentVO coefficentVO) {

        List<Coefficent> list = this.list(queryWrapper(coefficentVO));

        return list.stream().map(c->BeanConv.toBean(c, CoefficentVO.class)).collect(Collectors.toList());
    }

    @Override
    public CoefficentVO findByCoefficentKey(String coefficentKey) {
        //TODO
        return null;
    }

    /**
     * 分页 list 共用的wrapper
     * @param coefficentVO
     * @return
     */
    private LambdaQueryWrapper<Coefficent> queryWrapper(CoefficentVO coefficentVO){
        LambdaQueryWrapper<Coefficent> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(coefficentVO.getCoefficentKey()), Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
        .like(StrUtil.isNotBlank(coefficentVO.getCoefficentKeyName()), Coefficent::getCoefficentKeyName, coefficentVO.getCoefficentKeyName())
        .eq(StrUtil.isNotBlank(coefficentVO.getCoefficentKey()), Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey());
        return lqw;
    }

    /**
     *
     * @param coefficentKey
     */
    private int judgeMiddleTableDataExist(String coefficentKey) {

        Integer count = categoryCoefficentService.lambdaQuery()
                .eq(CategoryCoefficent::getCoefficentKey, coefficentKey)
                .count();

        Integer count1 = insuranceCoefficentService.lambdaQuery()
                .eq(InsuranceCoefficent::getCoefficentKey, coefficentKey)
                .count();

        if(count > 0 || count1 > 0){
            return 1;
        }

        return 0;

    }
}
